﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.SharePoint.Administration;

namespace Umbrella.Whs.SharePoint.WebConfigModifications
{
    internal sealed class EnableWhsFormsAuth : WebConfigModification
    {
        public override string Id
        {
            get { return "EnableWhsFormsAuth"; }
        }

        protected override IEnumerable<SPWebConfigModification> CreateInternal()
        {
            return new[]
            {
                new SPWebConfigModification()
                {
                    Name = "mode",
                    Path = "/configuration/system.web/authentication",
                    Value = "Forms",
                    Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute,
                },
                new SPWebConfigModification()
                {
                    Name = "forms",
                    Path = "/configuration/system.web/authentication",
                    Value = "<forms name=\"RemotePortalAuth\" loginUrl=\"/Remote/logon.aspx\" protection=\"All\" path=\"/\" timeout=\"12000\" requireSSL=\"false\" />",
                    Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
                },
                new SPWebConfigModification()
                {
                    Name = "machineKey",
                    Path = "/configuration/system.web",
                    Value = GetMachineKeyFromWhsWebsite(),
                    Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
                },
            };
        }

        private string GetMachineKeyFromWhsWebsite()
        {
            try
            {
                var xml = new XmlDocument();

                xml.Load(Properties.Constants.WhsWebsiteWebConfigPath);

                var machineKey = xml.SelectSingleNode("/configuration/system.web/machineKey") as XmlElement;

                if (machineKey == null)
                    throw new Exception("machineKey not found in WHS remote website web.config");

                return machineKey.OuterXml;

            }
            catch (Exception x)
            {
                _log.Error("Failed to retrieve machine key from WHS remote website", x);

                throw;
            }
        }
    }
}
